/*
	Copyright © 2008  Riztan Gutierrez <riztang@gmail.com>

   Este programa es software libre: usted puede redistribuirlo y/o modificarlo 
   conforme a los términos de la Licencia Pública General de GNU publicada por
   la Fundación para el Software Libre, ya sea la versión 3 de esta Licencia o 
   (a su elección) cualquier versión posterior.

   Este programa se distribuye con el deseo de que le resulte útil, pero 
   SIN GARANTÍAS DE NINGÚN TIPO; ni siquiera con las garantías implícitas de
   COMERCIABILIDAD o APTITUD PARA UN PROPÓSITO DETERMINADO. Para más información, 
   consulte la Licencia Pública General de GNU.

   http://www.gnu.org/licenses/
*/
/*
 *  SQLEdit().
 *
 */

#include "gclass.ch"
#include "hbclass.ch"
#include "proandsys.ch"

// GLOBAL EXTERNAL oTepuy
memvar oTepuy

/*
 * SQLEdit()
 */
/**\file SQLEdit.prg
 * \class SQLEdit. Clase SQLEdit
 *
 *  Clase para el reemplazo de Variables Publicas
 *  Esta basada en la clase original SQLEdit de
 *  Daniel Andrade Version 2.1
 *  
 *  \see Add().
 */
CLASS SQLEdit

   Public:

   METHOD New( lAutoAdd, lSensitive )          /**New(). */
   METHOD End()            INLINE ::Release()  /**End(). */ 

   METHOD SetConnection( oConn )
   METHOD RunSQL( cFile, p1,p2,p3,p4,p5,p6,p7,p8,p9,p10 )  
   METHOD RunText( cText )  
   METHOD OpenSQL( cFile, p1,p2,p3,p4,p5,p6,p7,p8,p9,p10 )  
   METHOD SaveSQL( cFile )  
   METHOD SaveSQLAs( cFile )  

   ERROR HANDLER OnError( cMsg, nError )

ENDCLASS


/*
 *  SQLEdit:New()
 */
/** Metodo Constructor.
 *  Permite generar la instancia de un objeto SQLEdit,
 *  Se puede inicializar con los parametros lAutomatic y lSensitive, 
 *  para definir si permite la creacion de variables y si admite 
 *  sensibilidad a las mayusculas respectivamente.
*/
METHOD New( nMode, cType ) CLASS SQLEdit

   //FileChooser( GTK_FILE_CHOOSER_ACTION_OPEN, "SQL" )

   Local oFileChooser, cFile, cDialog
   Local cPath, cAction
   
   Default nMode := GTK_FILE_CHOOSER_ACTION_OPEN
   Default cType := "SQL"

   If !::SetConnection()
      Return NIL
   EndIf
   
   DO CASE 
      CASE cType = "XBS"
         cPath   := "/xbscripts/*.xbs"
         cAction := "oTepuy:OpenXBS(cFile)"
      CASE cType = "SQL"
         cPath   := "/sql/*.sql"
         cAction := "OpenSQL(cFile)"
   ENDCASE
   
   SET RESOURCES oTepuy:cResource FROM FILE oTepuy:cRsrcMain 

//   MsgInfo( CStr(OSDRIVE() + "/" +CurDir()+"/xbscripts/") )

   If nMode = GTK_FILE_CHOOSER_ACTION_OPEN
      cDialog := "filechooserdialog0"
   Else
      cDialog := "filechooserdialog1"
   EndIf
      DEFINE FILECHOOSERBUTTON oFileChooser ID cDialog ;
          RESOURCE oTepuy:cResource;
          PATH_INIT OSDRIVE() + "/" +CurDir()+cPath
          
//          oFileChooser:SetIconName("gtk_preferences")

          DEFINE BUTTON ID "button_abrir" RESOURCE oTepuy:cResource;
                 ACTION (cFile:= oFileChooser:GetFileName(), oFileChooser:End(),;
                         IIF(cType = "XBS", oTepuy:OpenXBS(cFile), ;
                                            ::OpenSQL(cFile) ) )

          DEFINE BUTTON ID "button_cancelar" RESOURCE oTepuy:cResource;
                 ACTION oFileChooser:End()

    SysRefresh()


RETURN Self


/** SetConnection()
 *
 */
METHOD SetConnection( oConn ) CLASS SQLEdit

   Default oConn := oTepuy:aConnection[1]

   If Empty( oTepuy:aConnection )
      MsgStop( MSG_NO_CONNECTION, MSG_TITLE_ERROR )
      Return .F.
   EndIf
   
Return .T.


/** RunSQL()
 *
 */
METHOD RunSQL( cFile, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10 ) CLASS SQLEdit


Return View("RunSQL")


/** OpenSQL()
 *
 */
METHOD OpenSQL( cFile, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10 ) CLASS SQLEdit

   Local oWnd, oBox, oBoxLeft, oTextView, oScroll, oSourceView, oBtn, result, cText:=""
   Local cResource
   Local oBtn_Play, oBtn_Save, oBtn_SaveAs, oBtn_Prefe, oBtn_Exit
   Local oModel
   Local aStruct   := { {"Esquema","C",10,0}, {"","L",1,0} }
   Local aActions  := {'Msg_Info("SIIII")', {|| Msg_Info("Aloo") } } 
   Local aItems    := { { "public", .f.}, { "otro", .t.} }
   

   cText := MemoRead(cFile)
   
   oModel := Tpy_Data_Model():New( ,aStruct, aItems, aActions  )
   

   If File( cFile ) .AND. !Empty( cText )
      SET RESOURCES cResource FROM FILE oTepuy:cResources+"xbscript.glade"

      DEFINE WINDOW oWnd TITLE cFile+" - "+oTepuy:cSystem_Name ;
             ID "window1" RESOURCE cResource  SIZE 800,500
             
             DEFINE BOX oBoxLeft ID "vboxleft" RESOURCE cResource
                    oModel:Listore( oBoxLeft )
          
             DEFINE BUTTON oBtn_Play ID "toolbutton_ejecutar" RESOURCE cResource;
                    ACTION MsgInfo("Ejecutar...")
          
             DEFINE BUTTON oBtn_Save ID "toolbutton_guardar" RESOURCE cResource; 
                    ACTION ::SaveSQL( cFile )
          
             DEFINE BUTTON oBtn_SaveAs ID "toolbutton_guardar_como" RESOURCE cResource; 
                    ACTION ::SaveSQLAs( cFile )
          
             DEFINE BUTTON oBtn_Prefe ID "toolbutton_preferencias" RESOURCE cResource; 
                    ACTION ::SetConnection()
          
             DEFINE BUTTON oBtn_Exit ID "toolbutton_salir" RESOURCE cResource; 
                    ACTION oWnd:End() 
          
             DEFINE BOX oBox OF oWnd VERTICAL
          
             DEFINE SCROLLEDWINDOW oScroll OF oBox CONTAINER ;
                    ID "scrolledwindow1" RESOURCE cResource
          
             DEFINE SOURCEVIEW oSourceView VAR cText OF oScroll CONTAINER;
                    MIME "text/x-sql"
          
      ACTIVATE WINDOW oWnd CENTER ;
         VALID MsgNoYes(MSG_EXIT_WANT, MSG_TITLE_PLEASE_CONFIRM ) 

   EndIf


Return .T.


/** RunText()
 *
 */
METHOD RunText( cText ) CLASS SQLEdit

Return View("RunText")


/** SaveSQL()
 *
 */
METHOD SaveSQL( cFile, cText, lRefresh , oWnd )

Return View( "SaveSQL" )


/** SaveSQLAs()
 *
 */
METHOD SaveSQLAs( cText , oWnd )
   
RETURN View( "SaveSQL As" )


/**
 *  OnError()
 */
METHOD OnError( uValue,nError,nPar3,nPar4,nPar5,nPar6,nPar7,nPar8,nPar9,nPar10,nPar11 ) CLASS SQLEdit

  Local cMsg   := UPPE(ALLTRIM(__GetMessage()))
  //Local cMsg2  := Subs(cMsg,2)

  View( cMsg )

RETURN NIL




//////////////////  ESTO ES TEMPORAL
FUNCTION Create_Model()
  local oLbx
  local aParent, aChild , aIter
  local nMonth, nDay, pixbuf
  local nToday  := 0
  local aDays   := { "Lunes", "Martes", "Miercoles", "Jueves", ;
                     "Viernes", "Sabado", "Domingo" }
  local aMonths := { "Ene", "Feb", "Mar", "Abr", "May", "Jun", ;
                     "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" }

  DEFINE TREE_STORE oLbx TYPES G_TYPE_STRING, G_TYPE_BOOLEAN, GDK_TYPE_PIXBUF , G_TYPE_INT

  pixbuf := gdk_pixbuf_new_from_file( "/home/riztan/t-gtk/test/images/gnome-gsame.png" )

  for nMonth := 1 to len( aMonths )
      
      APPEND TREE_STORE oLbx ITER aParent VALUES aMonths[nMonth]
      SET TREE_STORE oLbx ITER aParent POS 4 VALUE 50
      
      for nDay := 1 to 30
          if nToday == 7
             SET TREE_STORE oLbx ITER aParent POS 2 VALUE .T.
             nToday  = 1
          else
             nToday += 1
          endif
           SET TREE_STORE oLbx ITER aParent POS 2 VALUE .T.
      
           APPEND TREE_STORE oLbx PARENT aParent ;
                  ITER aChild ;
                  VALUES aDays[nToday] + " " +;
                         str(nDay,2) + " de " + aMonths[nMonth] + " de 2.005"
          if aDays[nToday] == "Sabado" .OR. aDays[nToday] == "Domingo"
             SET TREE_STORE oLbx ITER aChild POS 2 VALUE .T.
             SET TREE_STORE oLbx ITER aChild POS 3 VALUE pixbuf
             SET TREE_STORE oLbx ITER aChild POS 4 VALUE 100
          else
             SET TREE_STORE oLbx ITER aChild POS 4 VALUE nDay
          endif
      next
  next
  
  gdk_pixbuf_unref( pixbuf )
   
  /* Ejemplo de INSERTAR un padre y un par de hijos en la primera posicion */
  INSERT TREE_STORE oLbx ROW 1 ITER aParent           // Padre
  
  SET TREE_STORE oLbx ITER aParent POS 1 VALUE "Hola" // Valor Padre
  
  SET TREE_STORE oLbx ITER aParent POS 4 VALUE 75     // Valor de Progress
  
      INSERT TREE_STORE oLbx ROW 1 ;
             ITER aChild PARENT aParent ;
             VALUES "Hijo",.T.,pixbuf,100 // Hijo con valores directamente

          INSERT TREE_STORE oLbx ROW 1 ;
                 ITER aIter PARENT aChild ;
                 VALUES "SubHijo",.F.,,50 // Hijo con valores directamente

 Return oLbx

//EOF
